package com.hzb.erp.wechat.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.hzb.erp.common.enums.SettingCodeEnum;
import com.hzb.erp.common.service.SettingService;
import com.hzb.erp.sysservice.enums.SettingNameEnum;
import com.hzb.erp.wechat.config.MiniAppConfig;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Ryan 541720500@qq.com
 * description
 */
@Service
@AllArgsConstructor
@Slf4j
public class MiniappService {

    private final SettingService settingService;
    private static SettingService stSettingService;
    private static MiniAppConfig configFromYml;
    private static WxPayConfig payConfigFromYml;

    private final MiniAppConfig miniappConfig;

    @PostConstruct
    public void init() {
        stSettingService = settingService;
        if (miniappConfig != null && StringUtils.isNotBlank(miniappConfig.getAppId())) {

            // 公众号参数
            configFromYml = new MiniAppConfig();
            BeanUtils.copyProperties(miniappConfig, configFromYml);
            configFromYml.setName("default");

            // 以下是支付相关，不需要支付功能的不用在yml里配置
            payConfigFromYml = new WxPayConfig();
            BeanUtils.copyProperties(miniappConfig, payConfigFromYml);

        }
    }

    public static String getDefaultAppId() {
        MiniAppConfig config = getConfigByName("default");
        if (config == null) {
            throw new RuntimeException("配置参数APPID设置错误:");
        }
        return config.getAppId();
    }

    public static MiniAppConfig getConfigByName(String confName) {
        List<MiniAppConfig> configs = getConfigList();
        if (StringUtils.isBlank(confName)) {
            confName = "default";
        }
        for (MiniAppConfig conf : configs) {
            if (conf.getName().equals(confName)) {
                return conf;
            }
        }
        return null;
    }

    /**
     * 配置设置参数
     */
    public static void setConfig(WxMaService service) {
        List<MiniAppConfig> configs = getConfigList();
        service.setMultiConfigs(
                configs.stream()
                        .map(a -> {
                            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
//                WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
                            // 使用上面的配置时，需要同时引入jedis-lock的依赖，否则会报类无法找到的异常
                            config.setAppid(a.getAppId());
                            config.setSecret(a.getSecret());
                            config.setToken(a.getToken());
                            config.setAesKey(a.getAesKey());
                            config.setMsgDataFormat("JSON");
                            return config;
                        }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
    }

    /**
     * 从数据库加载配置信息
     */
    public static List<MiniAppConfig> getConfigList() {

        List<MiniAppConfig> configs = new ArrayList<>();
        // 演示版代码 先尝试从配置文件里获取参数
        if (configFromYml != null && StringUtils.isNotBlank(configFromYml.getAppId())) {
            configs.add(configFromYml);
            log.info("==============从配置文件获取微信配置: {}", configs);
            return configs;
        }
        // 从数据库获取公众号配置：
        Map<String, Object> settings = stSettingService.listOptionByCode(SettingCodeEnum.WX_MINIAPP_SETTING);
        if (settings == null) {
            throw new RuntimeException("未找到微信公众号配置wx_miniapp_setting");
        }
        // todo 增加微信小程序配置项 SettingNameEnum
        try {
            String wxAppId = settings.get(SettingNameEnum.WX_MP_APP_ID.getCode()).toString();
            if (!StringUtils.isBlank(wxAppId)) {
                MiniAppConfig defaultConf = new MiniAppConfig();
                defaultConf.setName("default");
                defaultConf.setAppId(wxAppId);
                defaultConf.setSecret(settings.get(SettingNameEnum.WX_MP_SECRET.getCode()).toString());
                defaultConf.setToken(settings.get(SettingNameEnum.WX_MP_TOKEN.getCode()).toString());
                defaultConf.setAesKey(settings.get(SettingNameEnum.WX_MP_AES_KEY.getCode()).toString());
                configs.add(defaultConf);
            }
        } catch (Exception e) {
            throw new RuntimeException("请检查数据表 setting_option 的微信配置项是否完整. Missing Wechat Setting Option In Table:setting_option");
        }
        log.info("==============获取微信配置: {}", configs);
        return configs;
    }

}
